package cn.edu.hstc.wm.ui.fragment;

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.widget.TextView;

import cn.edu.hstc.wm.R;
import cn.edu.hstc.wm.ui.base.BaseFragment;
import cn.edu.hstc.wm.utils.LogUtil;

/**
 * 加载失败页面,当加载数据失败时显示
 * 
 * @author CX
 * @since 2014-01-01
 */
public class LoadFailedFragment extends BaseFragment implements OnTouchListener {

	/**
	 * 使用该Fragment的都应该实现该接口,当点击刷新按钮时回调该方法
	 */
	public interface CallBack {
		/**
		 * 刷新数据
		 */
		public void flush();
	}

	private static final String TAG = LoadFailedFragment.class.getName();

	/** 加载失败 */
	private static LoadFailedFragment sFragment = null;

	/** 回调接口 */
	private CallBack mCallback = null;

	/** 根视图 */
	private View mRootView;

	/** 刷新按钮 */
	private TextView mFlushView;

	/** 向下滑动位置 */
	private float mSlideY = 0;

	/**
	 * 获取该实例
	 * 
	 * @param bundle
	 *            传递的参数
	 * @return
	 */
	public static LoadFailedFragment getInstance(Bundle bundle) {
		if (sFragment == null) {
			sFragment = new LoadFailedFragment();
		}
		sFragment.setArguments(bundle);
		return sFragment;
	}

	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		LogUtil.i(TAG, "onCreateView");
		mRootView = inflater.inflate(R.layout.load_failed_fragment, null);
		initView();

		return mRootView;
	}

	private void initView() {
		mFlushView = (TextView) mRootView.findViewById(R.id.tv_load_failed_flush);
		mFlushView.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				mCallback.flush();
			}
		});
		mRootView.setOnTouchListener(this);
	}

	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		LogUtil.i(TAG, "onActivityCreated");
		super.onActivityCreated(savedInstanceState);
	}

	@Override
	public void onAttach(Activity activity) {
		LogUtil.i(TAG, "onAttach");
		if (!(getParentFragment() instanceof CallBack)) {
			throw new IllegalStateException("parentFragment must implement fragment's callbacks.");
		}
		mCallback = (CallBack) getParentFragment();
		super.onAttach(activity);
	}

	@Override
	public void onDetach() {
		LogUtil.i(TAG, "onDetach");
		super.onDetach();
	}

	public boolean onTouch(View v, MotionEvent event) {
		switch (event.getAction()) {
		case MotionEvent.ACTION_DOWN:
			mSlideY = event.getY();
			break;

		case MotionEvent.ACTION_UP:
			if (event.getY() - mSlideY > 250) {
				mCallback.flush();
			}
			break;

		default:
			break;
		}

		return true;
	}

}
